'use strict';

// 有道翻译

const puppeteer = require('puppeteer');

function fy(text) {
    text = encodeURIComponent(text);
    const baseUrl = `https://www.youdao.com/result?word=${text}&lang=en`;
    return new Promise((reslove) => {
        (async () => {
            const browser = await puppeteer.launch();
            const page = await browser.newPage();
            await page.goto(baseUrl);
            await page.setViewport({width: 1080, height: 1024});
            const res = await page.evaluate(() => {
                let elems = document.querySelectorAll('.trans-content');
                const res = [];
                for (let i = 0; i < elems.length; i++) {
                    const elm = elems[i];
                    res.push(elm.innerText);
                }
                elems = document.querySelectorAll('#catalogue_author .word-exp .point');
                for (let i = 0; i < elems.length; i++) {
                    const elm = elems[i];
                    res.push(elm.innerText);
                }
                return res;
            });
            await browser.close();
            reslove(res);
        })();
    });
}

const args = process.argv;
if (args.length === 3) {
    fy(args[2]).then((res) => {
        console.log(JSON.stringify(res));
    });
}
